package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.NcOrderCfMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.util.*;

/**
 * 菜房订单 服务层实现
 *
 * @author ruoyi
 * @date 2019-08-29
 */
@Service
public class NcOrderCfServiceImpl implements INcOrderCfService {
    @Autowired
    private NcOrderCfMapper ncOrderCfMapper;

    @Autowired
    private INcCaiService ncCaiService;

    @Autowired
    private INcOrderService orderService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private INcPlanService planService;

    @Autowired
    private INcCaiService caiService;


    /**
     * 查询菜房订单信息
     *
     * @param cforderId 菜房订单ID
     * @return 菜房订单信息
     */
    @Override
    public NcOrderCf selectNcOrderCfById(Long cforderId) {
        return ncOrderCfMapper.selectNcOrderCfById(cforderId);
    }

    /**
     * 查询菜房订单列表
     *
     * @param ncOrderCf 菜房订单信息
     * @return 菜房订单集合
     */
    @Override
    public List<NcOrderCf> selectNcOrderCfList(NcOrderCf ncOrderCf) {
        return ncOrderCfMapper.selectNcOrderCfList(ncOrderCf);
    }

    /**
     * 新增菜房订单
     *
     * @param ncOrderCf 菜房订单信息
     * @return 结果
     */
    @Override
    public int insertNcOrderCf(NcOrderCf ncOrderCf) {
        return ncOrderCfMapper.insertNcOrderCf(ncOrderCf);
    }

    /**
     * 修改菜房订单
     *
     * @param ncOrderCf 菜房订单信息
     * @return 结果
     */
    @Override
    public int updateNcOrderCf(NcOrderCf ncOrderCf) {
        return ncOrderCfMapper.updateNcOrderCf(ncOrderCf);
    }

    /**
     * 删除菜房订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteNcOrderCfByIds(String ids) {
        return ncOrderCfMapper.deleteNcOrderCfByIds(Convert.toStrArray(ids));
    }

    @Override
    public NcOrderCf fillValues(NcOrderCf ncOrderCf) {
        //找到菜 并找到这个菜的父类，祖父类
        NcCai ncCai = ncCaiService.selectCaiById(ncOrderCf.getCropVarieties());
        if (ncCai == null || ncCai.getAncestors() == null || ncCai.getAncestors().split(",").length != 3) {
            return null;
        }
        //蔬菜名称
        NcCai cropNameBean = ncCaiService.selectCaiById(ncCai.getParentId());
        //蔬菜分类
        NcCai cropTypeBean = ncCaiService.selectCaiById(cropNameBean.getParentId());
        ncOrderCf.setCropVarietiesCn(ncCai.getCaiName());
        ncOrderCf.setCropNameCn(cropNameBean.getCaiName());
        //匹配计划
        ncOrderCf = matchPlan(ncOrderCf);
        return ncOrderCf;
    }

    /**
     * 匹配计划
     *
     * @param cfOrder
     * @return
     */
    private NcOrderCf matchPlan(NcOrderCf cfOrder) {
        NcPlan plan = new NcPlan();
        plan.setPlanType(2);
        plan.setCropVarieties(cfOrder.getCropVarieties());
        List<NcPlan> plans = planService.selectNcPlanList(plan);

        cfOrder.setHasPlan("2");
        cfOrder.setPlanId(null);
        if (plans != null && plans.size() > 0) {
            for (NcPlan p : plans) {
                if ("3".equals(plan.getStatus())) {
                    cfOrder.setPlanId(p.getPlanId().intValue());
                    cfOrder.setHasPlan("1");
                    break;
                }

            }
            if (cfOrder.getPlanId() == null || cfOrder.getPlanId() == 0) {
                cfOrder.setPlanId(plans.get(0).getPlanId().intValue());
                cfOrder.setHasPlan("1");
            }
        }

        return cfOrder;
    }

    @Override
    @Transactional
    public int createNcOrderCfByIds(String ids, SysUser user) {

        //TODO 把订单分为两种  生成两种订单 直供 内销
        NcOrderCf temp = new NcOrderCf();
        temp.getParams().put("ids", ids);
        List<NcOrderCf> cfs = selectNcOrderCfList(temp);

        List<NcOrderCf> zhiGongO = new ArrayList<>();
        List<NcOrderCf> neiXiaoO = new ArrayList<>();
        for (NcOrderCf allO : cfs) {
            if (allO.getCforderType() == 1) {
                zhiGongO.add(allO);
            } else {
                neiXiaoO.add(allO);
            }
        }

        if (zhiGongO.size() > 0) {
            saveAndUpdate(1, zhiGongO, user);
        }
        if (neiXiaoO.size() > 0) {
            saveAndUpdate(2, neiXiaoO, user);
        }
        return 1;
    }

    /*插入订单并更新每条菜的状态*/
    private void saveAndUpdate(Integer outType, List<NcOrderCf> list, SysUser user) {

        /*创建菜房订单*/
        NcOrder o = new NcOrder();
        o.setOutputType("" + outType);
        o.setOrderCode(NcUtils.getOrderCode());
        o.setOrderType(Constants.ORDER);
        o.setOrderTime(new Date());
        o.setCreateTime(new Date());
        o.setCreateBy(user.getUserName());
        o.setStatus(1);//执行中
        orderService.insertNcOrder(o);

        System.out.println("----------orderId-------:" + o.getOrderId());
        for (NcOrderCf orderCf : list) {
            orderCf.setOrderId(o.getOrderId());
            orderCf.setStatus("2");
            updateNcOrderCf(orderCf);
        }
    }

    @Override
    public void setOrderTypes(ModelMap mmap, NcOrderCf order, String orderStatus, int type) {
        List<SysDictData> cforderTypes = dictDataService.selectDictDataByType("cforderType");

        //key
        List<String> keys = new ArrayList<>();
        List<Integer> cf = new ArrayList<>();
        for (SysDictData d : cforderTypes) {
            keys.add(d.getDictLabel());
        }
        for (SysDictData d : cforderTypes) {
            order.setStatus("2");
            order.setCforderType(Integer.parseInt(d.getDictValue()));
            order.setCforderStatus(orderStatus);
            if (type != 2) {
                order.setIsCheck(2);
            }

            cf.add(ncOrderCfMapper.selectSum(order));
        }

        if (type == 2) {
            keys.add(0, "共计检测");
        } else {
            keys.add(0, "共计订单");
        }


        int total = 0;
        for (Integer i : cf) {
            total += i;
        }
        cf.add(0, total);


        List<Map> list = new ArrayList<>();

        for (int i = 0; i < keys.size(); i++) {
            Map m = new HashMap();
            if (i != 0) {
                m.put("type", cforderTypes.get(i - 1).getDictValue());
            } else {
                m.put("type", null);
            }

            m.put("key", keys.get(i));
            m.put("value", cf.get(i));
            m.put("class", (i + 1) + " " + (i == 0 ? "active" : ""));
            list.add(m);
        }
        mmap.put("cf", cf);
        mmap.put("keys", keys);
        mmap.put("list", list);

    }

    /**
     * 根据时间 把订单数量汇总
     *
     * @param orderType
     * @param spanType  1,2,3 年 月 日
     * @param beginTime
     * @param endTime
     * @param type
     * @return
     */
    @Override
    public List<Map> selectCountByTime(Integer orderType, Integer spanType, String beginTime, String endTime, int type) {

        Date s = null;
        Date e = null;
        Map se = calTimeSpan(s, e, beginTime, endTime, spanType);
        s = (Date) se.get("s");
        e = (Date) se.get("e");

        //检测
        if (type == 2) {
            return getSumByDate(spanType, s, e, orderType, "3,4,5,6,7,8,9", true);
        }
        return getSumByDate(spanType, s, e, orderType, null, false);
    }

    @Override
    public Map calTimeSpan(Date s, Date e, String beginTime, String endTime, Integer spanType) {
        //1、如果是存在结束时间 则请求数据为当结束时间向前推12个点（年月日）
        if (StringUtils.isNotEmpty(endTime)) {
            e = DateUtils.dateTime("yyyy-MM-dd", endTime);
            if (spanType == 1) {
                s = DateUtils.addYears(e, -11);
            } else if (spanType == 2) {
                s = DateUtils.addMonths(e, -11);
            } else if (spanType == 3) {
                s = DateUtils.addDays(e, -11);
            }

            //2、如果不存在结束时间，只存在开始时间  且开始时间到现在够12个点（年月日），则从开始时间到现在取12个点，不够12点的 从现在往前推12个点

        } else if (StringUtils.isNotEmpty(beginTime)) {
            s = DateUtils.dateTime("yyyy-MM-dd", beginTime);
            if (spanType == 1) {
                s = DateUtils.addYears(new Date(), -11);
                e = new Date();
            } else if (spanType == 2) {
                if (NcUtils.differentDaysByDate(new Date(), s) >= 336) {
                    e = DateUtils.addMonths(s, 11);
                } else {
                    s = DateUtils.addMonths(new Date(), -11);
                    e = new Date();
                }

            } else if (spanType == 3) {
                if (NcUtils.differentDaysByDate(new Date(), s) >= 11) {
                    e = DateUtils.addDays(s, 12);
                } else {
                    s = DateUtils.addDays(new Date(), -11);
                    e = new Date();
                }
            }

            //3 没有时间
        } else {
            if (spanType == 1) {
                s = DateUtils.addYears(new Date(), -11);
                e = new Date();
            } else if (spanType == 2) {
                s = DateUtils.addMonths(new Date(), -11);
                e = new Date();
            } else if (spanType == 3) {
                s = DateUtils.addDays(new Date(), -11);
                e = new Date();

            }
        }
        Map m = new HashMap();
        m.put("s", s);
        m.put("e", e);
        return m;
    }

    private List<Map> getSumByDate(Integer spanType, Date s, Date e, Integer orderType, String cforderStatus, boolean isCheck) {
        List<Map> result = new ArrayList<>();
        if (spanType == 1) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy", s);

                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("count", getSumByDate(dateSpan, spanType, orderType, cforderStatus, isCheck));
                result.add(m);

                s = DateUtils.addYears(s, 1);
            }
        } else if (spanType == 2) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy-MM", s);
                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("count", getSumByDate(dateSpan, spanType, orderType, cforderStatus, isCheck));
                result.add(m);
                s = DateUtils.addMonths(s, 1);
            }
        } else if (spanType == 3) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy-MM-dd", s);
                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("count", getSumByDate(dateSpan, spanType, orderType, cforderStatus, isCheck));
                result.add(m);
                s = DateUtils.addDays(s, 1);
            }
        }
        return result;
    }

    private Integer getSumByDate(String dateSpan, Integer dataSpan, Integer orderType, String cforderStatus, boolean isCheck) {
        NcOrderCf order = new NcOrderCf();
        if (dataSpan == null || dataSpan == 2) {
            order.getParams().put("dateSpanMonth", dateSpan);
        } else if (dataSpan == 1) {
            order.getParams().put("dateSpanYear", dateSpan);
        } else if (dataSpan == 3) {
            order.getParams().put("dateSpanDay", dateSpan);
        }
        order.setStatus("2");//已生成单子
        if (orderType != null && orderType > 0) {
            order.setCforderType(orderType);
        }
        order.setCforderStatus(cforderStatus);
        if (!isCheck)
            order.setIsCheck(2);
        return ncOrderCfMapper.selectSum(order);
    }

    @Override
    public String importOrder(List<NcOrderCf> orders, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(orders) || orders.size() == 0) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (NcOrderCf ncOrderCf : orders) {
            try {

                ncOrderCf.setCforderCode(NcUtils.getOrderCode());
                ncOrderCf.setCreateTime(new Date());
                ncOrderCf.setCreateBy(operName);

                if (1 == ncOrderCf.getCforderType()) {
                    ncOrderCf.setCforderFor(1);
                } else {
                    ncOrderCf.setCforderFor(2);
                }

                NcOrderCf temp = fillValuesCn(ncOrderCf);
                if (temp != null) {
                    ncOrderCf = temp;
                    //如果是鸡蛋或者牛奶则，设置订单的cforderStatus 为 待牛舍确认、或待鸡舍确认
                    NcCai ncCai = caiService.selectCaiById(ncOrderCf.getCropVarieties());
                    if (ncCai.getCode().startsWith("milk")) {
                        ncOrderCf.setCforderStatus("6");//牛舍待确认
                    } else if (ncCai.getCode().startsWith("chicken")) {
                        ncOrderCf.setCforderStatus("7");//鸡舍待确认
                    }


                    ncOrderCf.setStatus("1");
                    ncOrderCf.setCforderStatus("1");
                    int result = insertNcOrderCf(ncOrderCf);
                    if (result > 0) {
                        successNum++;
                    } else {
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、" + ncOrderCf.getCropNameCn() + "-" + ncOrderCf.getCropVarietiesCn() + "-订单导入失败：";
                        failureMsg.append(msg);
                    }
                } else {
                    //未找到品种
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、" + ncOrderCf.getCropNameCn() + "-" + ncOrderCf.getCropVarietiesCn() + "-未找到品种";

                    failureMsg.append(msg);
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "订单 " + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    @Override
    public Integer caiScreen(NcOrderCf order) {
        return ncOrderCfMapper.caiScreen(order);
    }


    /*根据中文的菜的名字和菜的品种进行匹配找到这个菜的id*/
    private NcOrderCf fillValuesCn(NcOrderCf ncOrderCf) {
        if (StringUtils.isEmpty(ncOrderCf.getCropNameCn()) || StringUtils.isEmpty(ncOrderCf.getCropVarietiesCn())) {
            return null;
        }
        NcCai temp = new NcCai();
        temp.getParams().put("cropNameCn", ncOrderCf.getCropNameCn());
        temp.getParams().put("cropVarietiesCn", ncOrderCf.getCropVarietiesCn());
        List<NcCai> cais = ncCaiService.selectCaiByNames(temp);
        if (cais == null || cais.size() == 0) {
            return null;
        }
        //找到菜 并找到这个菜的父类，祖父类
        NcCai ncCai = cais.get(0);
        if (ncCai == null || ncCai.getAncestors() == null || ncCai.getAncestors().split(",").length != 3) {
            return null;
        }
        ncOrderCf.setCropVarieties(ncCai.getCaiId());
        //匹配计划
        ncOrderCf = matchPlan(ncOrderCf);
        return ncOrderCf;
    }


}
